<template>
    <div class="echarts">
        <div style="width: 100%;height:100%;"></div>
    </div>
</template>

<script>
import * as echarts from 'echarts'
export default {
    props: {
        element: {
            type: Object,
        },
    },
    data() {
        return {
            myChart: null,
        }
    },
    computed: {
        isShow() {
            return this.element.option
        },
        isStyle() {
            return this.element.style
        },
    },
    watch: {
        isShow: {
            handler: function (val) {
                // 此处注意，handler函数不能为箭头函数，this会取上下文，而不是组件里的this,此外，深度监听，必须为handler函数名，否则会无效果
                // this.setEchartsColors(val)
                this.myChart.clear()
                this.myChart.setOption(val)
            },
            deep: true,
        },
        '$store.state.echartsChange': function (e) {
            this.myChart.resize({ animation: { duration: 500 } }) //echarts自适应动画
        },
        '$store.state.canvasStyleData': function (e) {
            this.myChart.resize({ animation: { duration: 500 } }) //echarts自适应动画
        },
    },
    methods: {
        setEchartsColors(option) {
            option.series.forEach(item => {
                let data = Math.max(...item.data)
                item.itemStyle.color = function (p) {
                    if (p.value !== data) {
                        return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                            { offset: 0, color: option.color[0] },
                            { offset: 1, color: option.color[1] },
                        ])
                    } else {
                        return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                            { offset: 0, color: option.color[4] },
                            { offset: 1, color: option.color[3] },
                        ])
                    }
                }
            })
        },
    },
    created() {},
    mounted() {
        this.setEchartsColors(this.element.option)
        if (this.$store.state.editMode == 'preview') {
            this.myChart = echarts.init(document.getElementById('preview' + this.element.id))
        } else {
            this.myChart = echarts.init(document.getElementById('component' + this.element.id))
        }
        this.myChart.setOption(this.element.option)
    },
    beforeCreate() {},
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    components: {},
}
</script>

<style lang='scss' scoped>
.echarts {
    width: 100%;
    height: 100%;
    overflow: auto;
}
::-webkit-scrollbar {
    display: none;
}
</style>